# coding: utf-8

import json

import time
from flask import request

from fralog.FraLog import getFileLog
from exceptions.fra_exception import FraException
from settings import *
from dbproxy.dbproxy import *

log = getFileLog()


#
# 根据题号/题目属性(标准特征)查询标准题目
# 保存标准题目


class StandardQuestion(object):
    """
    模型题库相关操作的接口功能均封装在此
    """
    table_name = 'questions_collection'

    def __init__(self):
        super(StandardQuestion, self).__init__()
        self.db_proxy = DBProxy(db=mongo)

    def query_all_questions_by(self, question_type, question_id, pagesize, page, company_id=None):
        """
        查询所有的题目 根据type和id,缺省也可查询
        :return:
        """
        sort = [("question_id", pymongo.DESCENDING)]
        log.debug('查询模型题库题目')
        if question_type is not None and question_type != '':
            question_type = int(question_type)
        if question_type is not None and question_type == '':
            question_type = None
        query = {}
        if company_id is not None:
            query['company_id'] = company_id
        if question_id is None and question_type is None:
            query['question_type'] = {'$lte': 2}
            ret = self.db_proxy.page_query(table=self.table_name, sort=sort,
                                           query=query,
                                           # {'question_type': {'$lte': 2}},
                                           page=page,
                                           pagesize=pagesize)
        if question_id is not None and question_type is not None:
            query['question_id'] = question_id
            query['question_type'] = question_type
            ret = self.db_proxy.page_query(table=self.table_name,  sort=sort,
                                           query=query,
                                           # {'question_id': question_id,  'question_type': question_type},
                                           page=page,
                                           pagesize=pagesize)
        if question_id is None and question_type is not None:
            query['question_type'] = question_type
            ret = self.db_proxy.page_query(table=self.table_name,  sort=sort,
                                           query=query,
                                           # {'question_type': question_type},
                                           page=page,
                                           pagesize=pagesize)
        if question_id is not None and question_type is None:
            query['question_type'] = {'$lte': 2}
            query['question_id'] = question_id
            ret = self.db_proxy.page_query(table=self.table_name,  sort=sort,
                                           query=query,
                                           # {'question_type': {'$lte': 2}, 'question_id': question_id},
                                           page=page, pagesize=pagesize)
        log.debug('查询模型题库题目成功返回')
        return ret

    def query_question_detail(self, question_id):
        log.debug('查询模型题目明细: %s' % (question_id))
        ret = self.db_proxy.query_one(table=self.table_name, query={'question_id': int(question_id)})
        log.debug('题目模型明细查询结束')
        return ret

    def question_edit(self, question_id, setvalue, insert_not_found=False):
        log.debug('编辑模型题目')
        ret = self.db_proxy.update(table=self.table_name, query={'question_id': int(question_id)}, setvalue=setvalue,
                                   insert_not_found=insert_not_found)
        return ret

    def question_delete(self, question_id):
        log.debug('删除模型题目: %s' % (question_id))
        ret = self.db_proxy.delete(table=self.table_name, query={'question_id': int(question_id)})
        return ret

    def query_desc_collection(self, field):
        """
        查询所有的题目
        :return:
        """
        log.debug('查询报告模板')
        ret = self.db_proxy.distinct(table='desc_collection', field=field, query={})
        print(ret)
        log.debug('查询模型题库成功返回')
        return ret

    def upsert_desc_collection(self, param):
        """
        查询所有的题目
        :return:
        """
        log.debug('查询报告模板')
        id = param.get('id')
        code = param.get('code')
        if param.get('token') is not None:
            del param['token']
        ret = self.db_proxy.update(table='desc_collection', query={'id': id, 'code': code}, setvalue=param,
                                   insert_not_found=True)
        print(ret)
        log.debug('查询模型题库成功返回')
        return ret

    def query_normal_collection(self):
        """
        查询所有的题目
        :return:
        """
        log.debug('查询常模模板')
        ret = self.db_proxy.page_query(table='normal_collection', query={})
        print(ret)
        log.debug('查询常模模板成功返回')
        return ret

    def upsert_normal_collection(self, param):
        """
        查询所有的题目
        :return:
        """
        log.debug('新增修改常模模板')
        code = param.get('code')
        del param['token']
        ret = self.db_proxy.update(table='normal_collection', query={'code': code}, setvalue=param,
                                   insert_not_found=True)
        print(ret)
        log.debug('新增修改常模模板成功返回')
        return ret

    def query_longurl_collection(self, shorturl):
        """
        查询所有的题目
        :return:
        """
        log.debug('查询长短链接')
        if shorturl is None:
            ret = self.db_proxy.page_query(table='short_longurl_collection', query={}, pagesize=0)
        else:
            ret = self.db_proxy.page_query(table='short_longurl_collection', query={'shorturl': shorturl})
        print(ret)
        log.debug('查询长短链接成功返回')
        return ret

    def upsert_longurl_collection(self, param):
        """
        查询所有的题目
        :return:
        """
        log.debug('新增长短链接')
        shorturl = param.get('shorturl')
        ret = self.db_proxy.update(table='short_longurl_collection', query={'shorturl': shorturl},
                                   setvalue=param,
                                   insert_not_found=True)
        print(ret)
        log.debug('新增长短链接成功返回')
        return ret


standard_question = StandardQuestion()


@app.route('/sq/query_all_questions_by2', methods=['GET', 'POST'])
@verify_token
def sq_query_all_questions_by2():
    '''
    查询所有题目,如果question_type不填则返回客户和模型的所有题目
    输入(token默认输入): question_id question_type 缺省可不填
    返回:ret集合,ret.code=200,ret.data=[]
    :return:
    '''
    log.debug('选择查询模型题库')
    param = get_param(request)
    question_type = param.get('question_type')
    if question_type is not None and question_type != "":
        question_type = int(question_type)
    else:
        question_type = None
    question_id = param.get('question_id')
    if question_id is not None and question_id != "":
        question_id = int(question_id)
    else:
        question_id = None
    page = param.get('page')
    if page is not None:
        page = int(page)
    else:
        page = 1
    pagesize = param.get('pagesize')
    if pagesize is not None:
        pagesize = int(pagesize)
    else:
        pagesize = 500
    # title = param.get('title')
    return json.dumps(standard_question.query_all_questions_by(question_type, question_id, pagesize, page))


@app.route('/sq/query_all_questions_by', methods=['GET', 'POST'])
@verify_token
def sq_query_all_questions_by():
    '''
    查询所有题目,如果question_type不填则返回客户和模型的所有题目
    输入(token默认输入): question_type 缺省可不填
    返回:ret集合,ret.code=200,ret.data=[]
    :return:
    '''
    param = get_param(request)
    question_type = param.get('question_type')
    question_id = param.get('question_id')
    company_id = param.get('company_id')
    return json.dumps(standard_question.query_all_questions_by(question_type=question_type,
                                                               question_id=question_id, pagesize=0, page=1,company_id=company_id))


@app.route('/sq/query_question_detail', methods=['GET', 'POST'])
@verify_token
def sq_query_question_detail():
    '''
    查询单个题目
    输入(token默认输入): question_id必填
    返回:ret集合,ret.code=200,ret.data=[]
    :return:
    '''
    param = get_param(request)
    question_id = param.get('question_id')
    log.debug('模型问题ID: %s' % (question_id))
    return json.dumps(standard_question.query_question_detail(question_id))


@app.route('/sq/question_edit', methods=['GET', 'POST'])
@verify_token
def sq_question_edit():
    '''
    编辑单个题目
    输入(token默认输入): question_id必填
    返回:ret集合,ret.code=200,ret.data=[]
    :return:
    '''
    log.debug('模型问题编辑')
    param = get_param(request)
    question_id = param.get('question_id')
    data = param.get('data')
    current_time = time.localtime(time.time())
    timestr = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))
    data['update_time'] = timestr
    log.debug('参数成功获取，准备编辑')
    return json.dumps(standard_question.question_edit(question_id=question_id, setvalue=data))
    # if int(question_id) <= 657:
    #     ret = deepcopy(g_ret)
    #     ret['msg'] = '处理失败,暂时未开放657前的模型题目编辑'  # 中文标志
    #     return json.dumps(ret)
    # else:
    #     return json.dumps(standard_question.question_edit(question_id=question_id, setvalue=data))


@app.route('/sq/question_delete', methods=['GET', 'POST'])
@verify_token
def sq_question_delete():
    '''
    删除单个题目
    输入(token默认输入): question_id必填
    返回:ret集合,ret.code=200,ret.data=[]
    :return:
    '''
    log.debug('删除模型题目')
    param = get_param(request)
    question_id = param.get('question_id')
    log.debug('题目模型编号: %s' % question_id)
    return json.dumps(standard_question.question_edit(question_id=question_id, setvalue={'question_type': 99}))
    # return json.dumps(standard_question.question_delete(question_id))


@app.route('/sq/query_desc_collection', methods=['GET', 'POST'])
@verify_token
def sq_query_desc_collection():
    '''
    查询报告模板distinct code
    输入(token默认输入):
    返回:ret集合,ret.code=200,ret.data=[{'code':''},{}]
    :return:
    '''
    log.debug('选择查询报告库')
    param = get_param(request)
    return json.dumps(standard_question.query_desc_collection(field='code'))


@app.route('/sq/query_longurl_collection', methods=['GET', 'POST'])
@verify_token
def sq_query_longurl_collection():
    '''
    查询长短链接列表
    输入(token默认输入):shorturl 可不填
    返回:ret集合,ret.code=200,ret.data=[{'code':''},{}]
    :return:
    '''
    log.debug(' ')
    param = get_param(request)
    # survey_type = param.get('survey_type') 
    return json.dumps(standard_question.query_longurl_collection(shorturl=param.get('shorturl')))


@app.route('/sq/query_normal_collection', methods=['GET', 'POST'])
@verify_token
def sq_query_normal_collection():
    '''
    查询常模系数模板列表
    输入(token默认输入):
    返回:ret集合,ret.code=200,ret.data=[{'code':''},{}]
    :return:
    '''
    log.debug(' ')
    param = get_param(request)
    # survey_type = param.get('survey_type') 
    return json.dumps(standard_question.query_normal_collection())


@app.route('/sq/upsert_desc_collection', methods=['GET', 'POST'])
@verify_token
def sq_upsert_desc_collection():
    '''
    新增或更新报告模板
    输入(token默认输入):param作为整个对象,必须包含code;code重复更新,没有则新增
    返回:ret集合,ret.code=200,ret.data=[{'code':''},{}]
    :return:
    '''
    log.debug(' ')
    param = get_param(request)
    # survey_type = param.get('survey_type') 
    return json.dumps(standard_question.upsert_desc_collection(param))


@app.route('/sq/upsert_longurl_collection', methods=['GET', 'POST'])
@verify_token
def sq_upsert_longurl_collection():
    '''
    新增或更新长短链接信息
    输入(token默认输入):shorturl重复更新,没有则新增
    返回:ret集合,ret.code=200,ret.data=[]
    :return:
    '''
    log.debug(' ')
    param = get_param(request)
    # survey_type = param.get('survey_type') 
    return json.dumps(standard_question.upsert_longurl_collection())


@app.route('/sq/upsert_normal_collection', methods=['GET', 'POST'])
@verify_token
def sq_upsert_normal_collection():
    '''
    新增或更新常模信息
    输入(token默认输入):code 重复更新,没有则新增
    返回:ret集合,ret.code=200,ret.data=[]
    :return:
    '''
    log.debug(' ')
    param = get_param(request)
    return json.dumps(standard_question.upsert_normal_collection(param))
